package com.schoolcloud.system.service.impl;

import com.schoolcloud.common.util.UserContext;
import com.schoolcloud.system.entity.SysPermission;
import com.schoolcloud.system.enums.SysPermissionTypeEnum;
import com.schoolcloud.system.mapper.SysPermissionMapper;
import com.schoolcloud.system.service.SysPermissionService;
import com.schoolcloud.system.service.SysRoleService;
import com.schoolcloud.system.vo.SysPermissionTreeVO;
import com.schoolcloud.system.vo.SysUserInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author hongmizfb
 * @description 针对表【sys_permission】的数据库操作Service实现
 * @createDate 2024-10-19 23:02:28
 */
@Service
@RequiredArgsConstructor
public class SysPermissionServiceImpl implements SysPermissionService {

    private final SysPermissionMapper permissionMapper;

    private final SysRoleService sysRoleService;

    @Override
    public void addPermission(SysPermission permission) {
        permission.setCreateBy(UserContext.getUser());
        permission.setCreateTime(new Date());
        permissionMapper.addPermission(permission);
    }

    @Override
    public List<SysPermissionTreeVO> convertedPermissionToTreeList(List<SysPermission> list) {
//        转换为子类
        List<SysPermissionTreeVO> vos = list.stream().map(item -> {
            SysPermissionTreeVO vo = new SysPermissionTreeVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(toList());
//        筛选出顶级权限
        List<SysPermissionTreeVO> collect = vos.stream().filter(item -> item.getParentId() == 0).collect(toList());
        return convertRecursion(collect, vos);
    }

    @Override
    public List<SysPermission> list() {
        return permissionMapper.all();
    }

    @Override
    public List<SysPermission> list(SysPermission sysPermission) {
        return permissionMapper.list(sysPermission);
    }

    @Override
    public List<String> getUserPermissionsCode(String userId) {
        return permissionMapper.getUserPermissionsCode(userId);
    }

    public List<SysPermission> getMenuByUserId(String userId) {
        return permissionMapper.getMenuByUserId(userId);
    }

    @Override
    public SysUserInfoVO getUserPermissions(String user) {
        SysUserInfoVO vo = new SysUserInfoVO();
        // 判断是否是超级管理员
        boolean isAdmin = sysRoleService.isAdmin(user);
        // 设置权限代码
        vo.setPermissionsCode(isAdmin ? listCode(null) : listCode(user));
        // 获取菜单列表
        List<SysPermission> permissions;
        if (isAdmin) {
            SysPermission sysPermission = new SysPermission();
            sysPermission.setPermissionType(SysPermissionTypeEnum.MENU.getCode());
            sysPermission.setIsShow(0);
            permissions = list(sysPermission);
        } else {
            permissions = getMenuByUserId(user);
        }
        if (permissions != null && permissions.size() > 0) {
            // 过滤出路由（菜单类型）
            List<SysPermission> routers = permissions.stream()
                    .filter(item -> item.getPermissionType() == SysPermissionTypeEnum.MENU.getCode())
                    .collect(toList());
            vo.setRouters(routers);
        }
        // 将权限集合转化为树结构
        assert permissions != null;
        List<SysPermissionTreeVO> treeVOS = convertedPermissionToTreeList(permissions);
        vo.setMenus(treeVOS);
        return vo;
    }

    @Override
    public List<SysPermission> getPermissionFolder() {
        return permissionMapper.getPermissionFolder();
    }

    @Override
    public void modifyPermission(SysPermission permission) {
        permissionMapper.modifyPermission(permission);
    }

    @Override
    public void delSysPermissionById(String permissionId) {
        permissionMapper.delSysPermissionById(permissionId);
    }

    @Override
    public List<SysPermission> getPermissionsByRoleId(String roleId) {
        return permissionMapper.getPermissionsByRoleId(roleId);
    }

    @Override
    public SysPermission getPermissionById(String permissionId) {
        return permissionMapper.getPermissionById(permissionId);
    }

    public List<String> listCode(String userId) {
        return permissionMapper.listCode(userId);
    }

    /**
     * 将给到的第一层权限处理为树结构
     *
     * @param parentList 第一层权限集合
     * @param havaList   拥有的所有权限集合
     * @return {@link List}<{@link SysPermissionTreeVO}>
     */
    private List<SysPermissionTreeVO> convertRecursion(List<SysPermissionTreeVO> parentList, List<SysPermissionTreeVO> havaList) {
        //遍历parentList从allList中寻找parentList元素的子元素，并放入children属性值
        parentList.forEach(item -> {
//            当前元素的子元素
            List<SysPermissionTreeVO> collect = havaList.stream().filter(item2 -> item2.getParentId().equals(item.getPermissionId())).collect(toList());
//            继续调用这个函数，查询子元素的子元素集合
            if (collect.size() > 0) {
                convertRecursion(collect, havaList);
            }
            //            将子元素集合装入这个父元素集合
            item.setChildren(collect);
        });
        return parentList;
    }
}
